import BuildForm from '@/components/BuildForm/BuildForm';
import FormattedMessageCustom from '@/components/FormattedMessageCustom/FormattedMessageCustom';
import { CONFIG } from '@/constants';
import { mapForm, mapFormItems } from '@/pages/order/buildFormItems';
import { getUserInfo, profile } from '@/servers/api/userController';
import { formFormat, isBase64, toImages } from '@/utils';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { getLocale, history, useIntl, useModel } from '@umijs/max';
import { Button, GetProp, Spin, Upload, UploadProps, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { formItemsConst } from './item';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const NewsForm: React.FC = () => {
    const lang = getLocale();
    const intl = useIntl();
    const [loading, setloading] = useState(false);
    const formItems = useRef();
    const [form, setForm] = useState();
    const { initialState, setInitialState }: any = useModel('@@initialState');
    const { user } = initialState;
    const [avatar, setavatar] = useState<string | null>();
    function onFinish(val: IBuildForm.IDefault) {
        const params = formFormat(val, formItems.current);
        setloading(true);
        profile({
            ...params,
            avatar: isBase64(avatar) ? null : avatar,
        })
            .then(async () => {
                setloading(false);
                message.success(intl.formatMessage({ id: '操作成功' }));
                const userData: IGlobal.IUser = await getUserInfo();
                setInitialState({
                    ...initialState,
                    user: userData.data,
                });
                history.push('/home');
            })
            .catch((err) => {
                message.error(err.msg);
                setloading(false);
            });
    }
    useEffect(() => {
        if (user) {
            let temp = JSON.parse(JSON.stringify(formItemsConst));
            formItems.current = temp;
            setavatar(toImages(user.avatar));
            if (lang === 'zh-CN') {
                for (let i = 0; i < formItems.current.length; i++) {
                    if (formItems.current[i].key === 'passport_code') {
                        formItems.current[i] = {
                            key: 'idnum',
                            label: '身份证号',
                            placeholder: '',
                            type: 'text',
                            required: false,
                            value: [],
                            rules: {},
                        };
                    }
                    if (formItems.current[i].key === 'passport_image') {
                        formItems.current.splice(i, 1);
                    }
                }
            }
            mapFormItems(formItems.current, user, intl).then((mapRes) => {
                formItems.current = mapRes;
            });
            mapForm(formItems.current, 1).then((formRes) => {
                setForm(formRes);
            });
        }
    }, [user]);
    const [imgLoading, setImgLoading] = useState(false);

    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') {
            setImgLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            if (info.file.response.data) {
                // setavatar(info.file.response.data.url);
                setavatar(toImages(info.file.response.data.url));
            }
            // Get this url from response in real world.
            // getBase64Callback(info.file.originFileObj as FileType, (url) => {
            //     setImgLoading(false);
            //     setavatar(url);
            //     // setavatar(toImages(user.avatar));
            // });
        }
    };
    const beforeUpload = (file: FileType) => {
        const isJpgOrPng =
            file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {imgLoading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );
    return (
        <Spin spinning={loading}>
            <div style={{ textAlign: 'center', marginBottom: 50 }}>
                <Upload
                    style={{ width: 'auto' }}
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action={CONFIG.HTTP_REQUEST_URL + '/common/upload'}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                >
                    {avatar ? (
                        <img
                            src={avatar}
                            alt="avatar"
                            style={{ width: '100%', height: '100%' }}
                        />
                    ) : (
                        uploadButton
                    )}
                </Upload>
            </div>

            <BuildForm
                formItems={formItems.current}
                value={form}
                onFinish={onFinish}
            >
                <Button type="primary" htmlType="submit">
                    <FormattedMessageCustom id="保存更改"></FormattedMessageCustom>
                </Button>
            </BuildForm>
        </Spin>
    );
};
export default NewsForm;
